﻿(function ($) {
    var r = 0;
    $.fn.extend({
        thumbchange: function (options) {
            var defaults = {
                delay: 600,
                attrname: 'data-count',
                startIndex: 1
            };
            var options = $.extend(defaults, options);
            function Preload(object, paths) {
                for (var i = 0; i < paths.length; i++) {
                    object.data('images')[i] = new Image();
                    setTimeout((function (obj, path, j) {
                        return function () { obj.data('images')[j].src = path; }
                    })(object, paths[i], i), i * options.delay / 2);
                }
            }
            function Change(object, index) {
                if (object.data('running')) {
                    var images = object.data('images');
                    if (images[index].src.length > 0 && images[index].complete) {
                        object.attr('src', images[index].src);
                        setTimeout((function (obj, ind) {
                            return function () { Change(obj, ind); }
                        })(object, index >= images.length - 1 ? 0 : index + 1), options.delay);
                    }
                    else {
                        setTimeout((function (obj, ind) {
                            return function () { Change(obj, ind); }
                        })(object, index), options.delay / 2);
                    }
                }
            }
            return this.each(function () {
                $(this).hover(function () {
                    var count = $(this).attr(options.attrname);
                    var src = $(this).attr('src');
                    var left = src.substring(0, src.lastIndexOf('-') + 1);
                    var right = src.substring(src.lastIndexOf('.'), src.length);
                    var paths = new Array();
                    for (var i = 1; i <= count; i++) {
                        paths[i - 1] = left + i + right;
                    }
                    if (options.startIndex >= 0 && options.startIndex < paths.length) {

                        $(this).data('running', true);
                        $(this).data('origsrc', $(this).attr('src'));
                        $(this).data('images', new Array());

                        Preload($(this), paths);
                        Change($(this), options.startIndex);

                    }
                }, function () {
                    $(this).data('running', false);
                    $(this).attr('src', $(this).data('origsrc'));
                });
            });
        }
    });
    $(function () {
        $('.thumbchange').thumbchange();
    });
})(jQuery);

